<?php

/*
 * newsletter.php
 */

$c = mysql_connect('localhost', 'root', '') or die("Connexion impossible au serveur");
mysql_select_db('sandbox') or die("Impossible de se connecter à la base de données");

$newsletter = !is_numeric($_GET['newsletter']) ? 0 : (int) $_GET['newsletter'];
$n = addslashes($_GET['newsletter']);

$email = $_GET['email'];

$sql = "SELECT * FROM newsletter WHERE id = $newsletter OR nom LIKE '$n'";
//var_dump($sql);
$resultNews = mysql_query($sql, $c) or die(mysql_error());
$newsletter = mysql_fetch_assoc($resultNews);

// HEADER image/jpg
header('Content-type:image/jpg');

if ($newsletter) {
    $nomNews = addslashes($newsletter['nom']);
    $sql = "SELECT * FROM statistiques WHERE nom_newsletter LIKE '$nomNews' AND email = '$email'";
    $resultStat = mysql_query($sql, $c) or die(mysql_error());
    $count = mysql_num_rows($resultStat);
    if ($count > 0) {
        $stat = mysql_fetch_assoc($resultStat);
        $nbOuverture = (int) $stat['nb_ouverture'] + 1;
        //var_dump($nbOuverture);
        $sql = "UPDATE statistiques SET nb_ouverture = $nbOuverture WHERE nom_newsletter LIKE '$nomNews' AND email = '$email'";
        $resultUpdate = mysql_query($sql) or die(mysql_error());
        $countUpdate = mysql_affected_rows($c);
        //echo 'img.jpg');
        readfile('img.jpg');
    } else {
        $sql = "INSERT INTO statistiques (nom_newsletter, email, nb_ouverture) VALUES('$nomNews', '$email', 1)";
        $resultInsert = mysql_query($sql, $c) or die(mysql_error());
        $countInsert = mysql_affected_rows($c);
        //echo $nomNews . '<br>';
        //echo 'img.jpg');
        readfile('img.jpg');
    }
}else{
    //var_dump($_GET['newsletter']);
    $nomNews = addslashes($_GET['newsletter']);
    $sql = "SELECT * FROM statistiques WHERE nom_newsletter LIKE '$nomNews' AND email = '$email'";
    $resultStat = mysql_query($sql, $c) or die(mysql_error());
    $count = mysql_num_rows($resultStat);
    if($count > 0){
        $stat = mysql_fetch_assoc($resultStat);
        $nbOuverture = (int) $stat['nb_ouverture'] + 1;
        //var_dump($nbOuverture);
        $sql = "UPDATE statistiques SET nb_ouverture = $nbOuverture WHERE nom_newsletter LIKE '$nomNews' AND email = '$email'";
        $resultUpdate = mysql_query($sql) or die(mysql_error());
        $countUpdate = mysql_affected_rows($c);
        //var_dump($sql);
        //echo 'img.jpg');
        readfile('img.jpg');
    }else{
        $sql = "INSERT INTO statistiques (nom_newsletter, email, nb_ouverture) VALUES('$nomNews', '$email', 1)";
        $resultInsert = mysql_query($sql, $c) or die(mysql_error());
        $countInsert = mysql_affected_rows($c);
        //echo $nomNews . '<br>';
        //var_dump($sql);
        //echo 'img.jpg');
        readfile('img.jpg');
    }
}


mysql_close();
